/**
 * @file util.js.
 * @author liaoxuezhi@baidu.com
 */
/* eslint-disable */

import * as isPlainObject from 'lodash/isPlainObject';
import * as objectKeys from 'lodash/keys';
import * as assign from 'object-assign';
import {evalExpression} from '../util';

export function filterOptions(options, data = {}) {
  return normalizeOptions(options)
    .map(item => {
      const disabledOn = item.disabledOn;

      delete item.disabledOn;

      if (!item.disabled && disabledOn) {
        item.disabled = evalExpression(disabledOn, data);
      }

      return item;
    })
    .filter(item => item.visibleOn ? evalExpression(item.visibleOn, data)
      : item.hiddenOn ? !evalExpression(item.hiddenOn, data) : true)
}

export function normalizeOptions(options) {
  if (!options) {
    return [];
  }

  if (typeof options === 'string') {
    return options.split(',').map(item => ({
      label: item,
      value: item
    }));
  } else if (isPlainObject(options)) {
    return objectKeys(options).map(key => ({
      label: key,
      value: options[key]
    }));
  } else if (!Array.isArray(options)) {
    return [];
  }

  return options.map(item => isPlainObject(item) ? assign({}, item, {
      value: String(item.value),
      label: item.hasOwnProperty('label') ? item.label : String(item.value)
    }) : {
      label: item,
      value: item
    });
}